//
//  KMPayTool.m
//  ycPRO
//
//  Created by fang.jiaxin on 15/11/19.
//
//

#import "KMPayTool.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"
#import "AppDelegate.h"
#import "QMSSGlobal.h"
#import "WXApi.h"

static KMPayTool *instance;

@implementation KMPayTool

+(KMPayTool *)sharedInstance
{
    if(!instance)
        instance = [[KMPayTool alloc] init];
    
    return instance;
}

- (void)sendWXPay:(NSDictionary *)kmOrder
{
//    if(!kmOrder.payment_package)
//    {
//        [CommonHelper showMessage:@"支付参数为空，无法完成支付" inView:MainApplication.window];
//        return;
//    }
   

        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [kmOrder objectForKey:@"appid"];
        req.partnerId           = [kmOrder objectForKey:@"partnerid"];
        req.prepayId            = [kmOrder objectForKey:@"prepayid"];
        req.nonceStr            = [kmOrder objectForKey:@"noncestr"];
        req.timeStamp           = [[kmOrder objectForKey:@"timestamp"] intValue];
        req.package             = @"Sign=WXPay";
        req.sign                = [kmOrder objectForKey:@"sign"];
        [WXApi sendReq:req];
        
        //日志输出
        NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
}

//客户端提示信息
//- (void)alert:(NSString *)title msg:(NSString *)msg
//{
//    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//    
//    [alter show];
//}

-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        alert.tag = 1000;
        [alert show];
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        
        //显示微信传过来的内容
        WXAppExtendObject *obj = msg.mediaObject;
        
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n缩略图:%zi bytes\n\n", msg.title, msg.description, obj.extInfo, msg.thumbData.length];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //从微信启动App
        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
        NSString *strMsg = @"这是从微信启动的消息";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}

-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                //[CommonHelper showMessage:@"订单支付成功" inView:MainApplication.window];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"PayCallBack" object:nil];
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                //[CommonHelper showMessage:@"订单支付失败" inView:MainApplication.window];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                alert.tag = 1000;
                [alert show];
                break;
        }
        
    }
    
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:UserUpdate object:resp];
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//    [alert show];
}





- (void)sendAliPay:(NSDictionary *)kmOrder
{
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088021692256940";
    NSString *seller = @"2088021692256940";
    NSString *privateKey = @"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMTMc8spPymwwGlygRw2twn3lOittvoeLXzk7pFZhWMcoNH9R1/7Cgyiew/jXfbd6bNETpGfheDWTOwNqt2ep5oBtTkLfkdrdcoFMqgm8+TNpXwr8YlmRP279E890JTtcmtndT784z9GOU64mckY01E0ABBWOXnuL2KQp+ixTO3jAgMBAAECgYBzMJi2WbY22NZG4lbgBMaudtQaPVPUosVNTVK2kQeaM6+OOgoFDBOdwZz2d8cQMGQSIfE7G3xpVgZARN+2SJ8gZunUR0C0CdCoCZo5gWI3PpakSZe96Ts4g4UbrvYHWQJ0m8qsqATNmbzRlSj8dNxH+iA9une4OsKsHjsvT1OQAQJBAOfSEyrUCKZAOsaJANYQIODyIWVpU1rJf5m29xMBieK61pOXO4587MFGiuXu9NLfhSWMF3t+omRrKA3exM8p+wECQQDZUz5SkFRgRdSwUAvSwptKTjd73hBYg9z1/v3OU+LYrfy79Cq1IVwV78DEPDJOOQKhbmutC8L3g8urXa9D31zjAkEA5GzCyEPQFglaIQEkmsmfrCfKMoQ7R00fd5arFMZCWPAjuaCeZcPBAp2BBhqUkSkAqMPG68AXQf24pRoqMbu7AQJBAJoSN/bUt9zg5N5ygU9UBD/zn8ZDMpduNLJ5qnoiYop3HtwpSDXNhrlOlf0JKCjopgLIg7HUys4rM7Mz4dNegT0CQQCmTzftJvpmo5VxptQA/D7Azj1lyTHf/SgdBDoXopW5XMhZuhgjmOBR6HZSey5Kl/bNFa0j+XP/VjdOG396R0ux";
//    /*============================================================================*/
//    /*============================================================================*/
//    /*============================================================================*/
//    
//    //partner和seller获取失败,提示
////    if ([partner length] == 0 ||
////        [seller length] == 0 ||
////        [privateKey length] == 0)
////    {
////        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
////                                                        message:@"缺少partner或者seller或者私钥。"
////                                                       delegate:self
////                                              cancelButtonTitle:@"确定"
////                                              otherButtonTitles:nil];
////        [alert show];
////        return;
////    }
////    KMCommodityClass *commodity = nil;
////    if(kmOrder.commodityArray.count>0)
////        commodity = kmOrder.commodityArray[0];
//    
//    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = [kmOrder objectForKey:@"orderNum"];//[((NSString *)[kmOrder objectForKey:@"orderNum"])stringByReplacingOccurrencesOfString:@"C" withString:@""]; //订单ID（由商家自行制定）
    order.productName = @"全民速送充值"; //商品标题
    order.productDescription = @"全民速送充值";//商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",[[kmOrder objectForKey:@"amount"] doubleValue]]; //商品价格
    order.notifyURL =  [NSString stringWithFormat:@"%@%@",URLDoman,@"payment/callback_alipay/"]; //回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    //order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"quanminsudi";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];

    
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            int statue = [[resultDic objectForKey:@"resultStatus"] intValue];
            if(statue == 9000)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"PayCallBack" object:kmOrder];
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"订单支付失败" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                alert.tag = 1000;
                [alert show];
            }
//            if(statue == 6001)
//                [CommonHelper showMessage:@"订单支付失败" inView:MainApplication.window];
//            
//            [[NSNotificationCenter defaultCenter] postNotificationName:UserUpdate object:resultDic];
        }];
    }

}

@end
